<template>
  <div id="container"></div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { getequipmentlist } from '@/api/echarts';

export default {
  name: "map-view",
  data() {
    return {
      map: null,
      markers: [],
      cluster: null,
    };
  },
  created() {
    this.initAMap();
  },
  methods: {
    async fetchEquipmentList() {
      try {
        const res = await getequipmentlist({ limit: 10000000 });
        if (!this.map) return; // 确保地图已经初始化

        this.markers = res.msg
          .filter(item => item.lat && item.lng)
          .map(item => new AMap.Marker({
            position: [parseFloat(item.lng), parseFloat(item.lat)],
            content: `<div class="amap-marker">${item.city || 'Unknown'}</div>`,
            // 设置标记的事件（可选）
          }));

        // 在地图初始化后添加标记
        this.addMarkers();
      } catch (error) {
        console.error('Error fetching equipment list:', error);
      }
    },
    initAMap() {
      AMapLoader.load({
        key: "f8c954755588cd09132500151dc4d01c",
        version: "2.0",
        plugins: ["AMap.Scale", "AMap.Geolocation", "AMap.MarkerClusterer"],
      }).then(AMap => {
        // 初始化地图
        this.map = new AMap.Map("container", {
          viewMode: "3D",
          zoom: 4,
          center: [116.397428, 39.90923],
          mapStyle: "amap://styles/blue",
        });

        this.map.addControl(new AMap.Scale());

        this.map.plugin('AMap.Geolocation', () => {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            buttonOffset: new AMap.Pixel(10, 20),
            zoomToAccuracy: true,
          });
          this.map.addControl(geolocation);
          geolocation.getCurrentPosition((status, result) => {
            if (status === 'complete') {
              this.map.setCenter(result.position);
            } else {
              console.error('Geolocation failed: ', result.message);
            }
          });
        });

        // 确保地图初始化完成后再获取数据
        this.fetchEquipmentList();
      }).catch(error => {
        console.log(error);
      });
    },
    addMarkers() {
      if (this.cluster) {
        this.cluster.clearMarkers(); // 清除现有的聚合
      }

      // 添加标记到地图
      this.markers.forEach(marker => marker.setMap(this.map));

      // 初始化聚合器
      this.cluster = new AMap.MarkerClusterer(this.map, this.markers, {
        gridSize: 80,
        zoomOnClick: true,
        styles: [{
          url: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
          size: new AMap.Size(32, 32),
          anchor: new AMap.Pixel(16, 16),
          textColor: '#fff',
          textSize: 14
        }]
      });
    },
  },
};
</script>

<style scoped>
#container {
  width: 100%;
  height: 100%;
}
.amap-marker {
  background-color: #ff3b30;
  color: white;
  padding: 5px;
  border-radius: 3px;
  font-size: 12px;
  text-align: center;
}
</style>
